﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Kators.BusinessObjects;
using Kators.Services;

namespace Kators
{
    public partial class PlayerInfo : Form
    {

        private List<Player> _players;
        private IList<Status> _playerStatus;
        private IList<Team> _teams;
        private IList<Position> _positions;
        private bool isNew = false;

        private string PlayerPictureFileExt;

        public PlayerInfo()
        {
            InitializeComponent();

        }

        private void PlayerInfo_Load(object sender, EventArgs e)
        {
            InitialDataBinding();

            UpdateNumberOfPlayers();

        }

        private void InitialDataBinding()
        {

            cmbBoxMonth.DataSource = DateTimeService.GetMonths();
            cmbBoxDay.DataSource = DateTimeService.GetDays();
            cmbBoxYear.DataSource = DateTimeService.GetYears(1960 /*startYear*/, 2001 /*endYear*/);

            _playerStatus = Status.GetFullTable();
            cmbBoxStatus.DataSource = _playerStatus;
            cmbBoxStatus.DisplayMember = "Description";

            //GetAllPlayers(); 

            _teams = Team.GetFullTable();
            cmbBoxTeams.DataSource = _teams;
            cmbBoxTeams.DisplayMember = "teamName";

            _positions = Position.GetFullTable();

        }

        private void GetAllPlayers()
        {
            _players = (List<Player>)Player.GetFullTable();
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = _players.OrderBy(x => x.FirstName).ToList();

        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            //UpdatePlayerProfile();
        }

        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            UpdatePlayerProfile();
        }

        private void UpdateNumberOfPlayers()
        {
            GetAllPlayers(); 

            lbTotalPlayers.Text = "Total Number of Players: " + Player.GetRowCountByCustomQuery("1=1");
            lbActivePlayers.Text = Player.GetRowCountByCustomQuery("statusId='" + Configuration.ActiveStatusId + "'").ToString();
            lbInActivePlayers.Text = Player.GetRowCountByCustomQuery("statusId='" + Configuration.InActiveStatusId + "'").ToString();

            lbPendingPlayers.Text = (Player.GetRowCountByCustomQuery("statusId='" + Configuration.PendingStatusId + "'") + Player.GetRowCountByCustomQuery("statusId is Null")).ToString();

            lbRetiredPlayers.Text = Player.GetRowCountByCustomQuery("statusId='" + Configuration.DeletedStatusId + "'").ToString();

            SetControlsEnable(false);

            dataGridView1.CurrentCell.Selected = false; 
        }

        private void UpdatePlayerProfile()
        {
            var selectedPlayer = (Player)dataGridView1.SelectedRows[0].DataBoundItem;
            Configuration.SelectedPlayerId = selectedPlayer.PlayerId;

            UpdatePlayerBio(selectedPlayer);
            UpdatePlayerStatus(selectedPlayer);
            UpdatePlayerTeam(selectedPlayer);
            UpdatePlayerPosition(selectedPlayer);
            UpdatePlayerPicture(selectedPlayer);
            UpdatePlayerTeamPicture(selectedPlayer);
        }

        private void UpdatePlayerBio(Player selectedPlayer)
        {
            txtFirstName.Text = selectedPlayer.FirstName;
            txtLastName.Text = selectedPlayer.LastName;

            if (!selectedPlayer.DOB.Equals(DateTime.MinValue))
            {
                cmbBoxMonth.SelectedIndex = selectedPlayer.DOB.Month - 1;
                cmbBoxDay.SelectedIndex = selectedPlayer.DOB.Day - 1;
                cmbBoxYear.SelectedIndex = cmbBoxYear.FindString(selectedPlayer.DOB.Year.ToString());

                var parsedDateTime = DateTimeService.GetParsedDateTime(selectedPlayer.DOB.Month.ToString(),
                                                                            selectedPlayer.DOB.Day.ToString(),
                                                                            selectedPlayer.DOB.Year.ToString());

                lbAge.Text = AgeService.GetAgeFromDateOfBirth(parsedDateTime).ToString();

            }
            else
            {
                cmbBoxMonth.SelectedIndex = -1;
                cmbBoxDay.SelectedIndex = -1;
                cmbBoxYear.SelectedIndex = -1;
                lbAge.Text = "Unknown";
            }
        }

        private void UpdatePlayerStatus(Player selectedPlayer)
        {
            try
            {
                var playerStatus = _playerStatus.FirstOrDefault(x => x.StatusId == selectedPlayer.StatusId);
                cmbBoxStatus.SelectedIndex = cmbBoxStatus.FindString(playerStatus.Description);
            }
            catch (Exception)
            {
                cmbBoxStatus.SelectedIndex = -1;
                cmbBoxStatus.Refresh();
            }
        }

        private void UpdatePlayerTeam(Player selectedPlayer)
        {
            try
            {
                var playerTeam = _teams.FirstOrDefault(x => x.TeamId == selectedPlayer.TeamId);
                cmbBoxTeams.SelectedIndex = cmbBoxTeams.FindString(playerTeam.TeamName);
            }
            catch (Exception)
            {

                cmbBoxTeams.SelectedIndex = -1;
                cmbBoxTeams.Refresh();
            }

        }

        private void UpdatePlayerPosition(Player selectedPlayer)
        {
            try
            {
                var position = _positions.FirstOrDefault(x => x.PositionId == selectedPlayer.PositionId);
                
                foreach (Control c in groupBox1.Controls)
                {
                    if (c.Text == position.Description)
                    {
                        RadioButton radio = c as RadioButton;
                        radio.Checked = true;
                    }
                }
            }
            catch (Exception)
            {
                rbtnNA.Checked = true;
            }
        }

        private void UpdatePlayerPicture(Player selectedPlayer)
        {
            try
            {   
                string pictureFile = selectedPlayer.PlayerId + selectedPlayer.PictureFileExt;
                string pictureFilePath = Path.Combine(Configuration.GetPlayerPicPath(), pictureFile);
                pictureBox1.Image = FileService.ShowPictureFile(pictureFilePath);

                PlayerPictureFileExt = selectedPlayer.PictureFileExt; 

            }
            catch (Exception)
            {

                pictureBox1.Image = new Bitmap(Configuration.GetNoPlayerPicturePath() );
            }

        }

        private void UpdatePlayerTeamPicture(Player selectedPlayer)
        {
            try
            {
                var team = Team.GetById(selectedPlayer.TeamId);
                string pictureFile = team.TeamId + team.LogoFileExt;
                string pictureFilePath = Path.Combine(Configuration.GetTeamLogoPath(), pictureFile);
                pictureBox2.Image = FileService.ShowPictureFile(pictureFilePath);

            }
            catch (Exception)
            {
                pictureBox2.Image = new Bitmap(Configuration.GetNoTeamLogoPath());
            }

        }

        private void SetControlsEnable(bool enable)
        {
            ControlsService.SetControls(gBoxPlayerInfo, "TextBox", enable);
            ControlsService.SetControls(gBoxPlayerInfo, "ComboBox", enable);
            ControlsService.SetControls(gBoxPlayerInfo, "RadioButton", enable);
            ControlsService.SetControls(gBoxPlayerInfo, "Button", enable);
            ControlsService.SetControls(gBoxTeamInfo, "ComboBox", enable);
            ControlsService.SetControls(gBoxUpdateAdd, "Button", enable);

        }


        private void btnUpdateTeam_Click(object sender, EventArgs e)
        {
            isNew = false;
            SetControlsEnable(true);


        }


        private void btnDelete_Click(object sender, EventArgs e)
        {
            var deletedPlayer = Player.GetById(Configuration.SelectedPlayerId);

            if (deletedPlayer != null)
            {
                DialogResult result =
                    MessageBox.Show(
                        "Do you really want to delete a player,\"" + deletedPlayer.FirstName + " " +
                        deletedPlayer.LastName + "\"?", "Kators -- Delete A Player",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    deletedPlayer.Delete();


                    string fileName = deletedPlayer.TeamId + deletedPlayer.PictureFileExt;
                    string targetFilePath = Path.Combine(Configuration.GetTeamLogoPath(), fileName);
                    pictureBox1.Image = null;

                    File.Delete(targetFilePath);

                    //MessageBox.Show("A player, \"" + deletedPlayer.FirstName + " " + deletedPlayer.LastName + "\" is deleted successfully.");

                    UpdateNumberOfPlayers();
                    dataGridView1.Rows[0].Selected = true;

                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            isNew = true;
            SetControlsEnable(true);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            SetControlsEnable(false);
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (isNew)
            {
                var newPlayer = new Player();
                Confirm(newPlayer);

            }
            else //update
            {
                var selectedPlayer =  Player.GetById (Configuration.SelectedPlayerId);
                Confirm(selectedPlayer);

            }

        }

        private void Confirm(Player player)
        {

            player.FirstName = txtFirstName.Text;
            player.LastName = txtLastName.Text;

            if (cmbBoxMonth.SelectedItem != null && cmbBoxDay.SelectedItem != null &&
                cmbBoxYear.SelectedItem != null)
            {
                player.DOB = DateTimeService.GetParsedDateTime(cmbBoxMonth.SelectedItem.ToString(),
                                                                  cmbBoxDay.SelectedItem.ToString(),
                                                                  cmbBoxYear.SelectedItem.ToString());
            }

            var status = cmbBoxStatus.SelectedItem as Status;
            player.StatusId = _playerStatus.First(x => x.Description == status.Description).StatusId;

            var position = groupBox1.Controls.OfType<RadioButton>().FirstOrDefault(x => x.Checked);
            if (position != null)
            {
                player.PositionId = _positions.FirstOrDefault(x => x.Description == position.Text).PositionId;
            }
            else
            {
                player.PositionId = _positions.First(x => x.Description == "N/A").PositionId;
            }

            player.PictureFileExt = PlayerPictureFileExt;

            var teamName = cmbBoxTeams.SelectedItem as Team;
            player.TeamId = _teams.First(x => x.TeamName == teamName.TeamName).TeamId;

            if (player.Save())
            {
                string fileName = player.PlayerId + player.PictureFileExt;
                string targetFilePath = Path.Combine(Configuration.GetPlayerPicPath(), fileName);

                try
                {
                    File.Copy(Configuration.SourceFilePath, targetFilePath);

                    UpdateNumberOfPlayers();
                    SelectNewPlayer();
                    if (isNew)
                    {
                        MessageBox.Show("Congrats! A new player is added.");
                    }
                    else
                    {
                        MessageBox.Show("A player is updated.");
                    }
                }
                catch
                {
                    MessageBox.Show("picture file copy is failed.");
                }

            }
            else
            {
                if (isNew)
                {
                    MessageBox.Show("Adding a new player into database is failed. Try again?");
                }
                else
                {
                    MessageBox.Show("Updating a player in database is failed. Try again?");
                }
            }





        }




        private void SelectNewPlayer()
        {

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                var cellFirstName = row.Cells["firstName"].Value;
                var cellLastName = row.Cells["lastName"].Value;
                if (cellFirstName.Equals(txtFirstName.Text) && cellLastName.Equals(txtLastName.Text))
                {
                    dataGridView1.Rows[row.Index].Selected = true;
                }
            }

        }

        private void cmbBoxYear_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (cmbBoxMonth.SelectedItem != null && cmbBoxDay.SelectedItem != null &&
                cmbBoxYear.SelectedItem != null)
            {
                var parsedDateTime = DateTimeService.GetParsedDateTime(cmbBoxMonth.SelectedItem.ToString(),
                                                                            cmbBoxDay.SelectedItem.ToString(),
                                                                            cmbBoxYear.SelectedItem.ToString());
                lbAge.Text = AgeService.GetAgeFromDateOfBirth(parsedDateTime).ToString();

            }


        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            string query = txtSearch.Text.ToLower().Trim();

            if (!string.IsNullOrEmpty(query))
            {
                var matchedPlayers = _players.FindAll(x => x.FirstName.ToLower().Contains(query));
                //var sortedPlayers = matchedPlayers.OrderBy(x => x.FirstName).ToList();
                dataGridView1.DataSource = matchedPlayers.OrderBy(x => x.FirstName).ToList();
            }
            else
            {
                dataGridView1.DataSource = _players;
            }

        }

        private void btnBrowser_Click(object sender, EventArgs e)
        {

            Configuration.SourceFilePath = FileService.BrowsingFilePath();

            if (Configuration.SourceFilePath != null)
            {
                //PlayerPictureFileExt = txtFirstName.Text + "_" + txtLastName.Text + "_" + DateTime.Now.Ticks +
                //                           Path.GetExtension(Configuration.SourceFilePath);
                PlayerPictureFileExt =Path.GetExtension(Configuration.SourceFilePath);
                pictureBox1.Image = new Bitmap(Configuration.SourceFilePath);
            }
        }

        private void cmbBoxTeams_SelectedIndexChanged(object sender, EventArgs e)
        {

            try
            {
                var team = cmbBoxTeams.SelectedItem as Team;
                
                //TeamPictureFileName = team.LogoFileName; 
                pictureBox2.Image = new Bitmap(team.LogoFileExt);
            }
            catch (Exception)
            {

                pictureBox2.Image = new Bitmap(Configuration.GetNoTeamLogoPath());
            }
        }

       



    }
}
